//
//  TFTableViewCollectionItemManager.m
//  AppLibs
//
//  Created by 杜恺 on 2018/7/30.
//  Copyright © 2018年 jack Kong. All rights reserved.
//

#import "TFTableViewCollectionItemManager.h"

@interface TFTableViewCollectionItemManager ()

@property (nonatomic, strong) NSMutableDictionary *reusableItemViewsEntry;

@end

@implementation TFTableViewCollectionItemManager

- (instancetype)initWithCollectionItemsArray:(NSArray<__kindof TFTableViewCollectionItem *> *)collectionItemsArray {
    self = [super init];
    if (self) {
        self.collectionItemsArray = collectionItemsArray;
    }
    return self;
}

- (void)setCollectionItemsArray:(NSArray<__kindof TFTableViewCollectionItem *> *)collectionItemsArray {
    _collectionItemsArray = collectionItemsArray;
    for (TFTableViewCollectionItem *item in collectionItemsArray) {
        item.manager = self;
    }
}

- (UIView *)dequeueReusableItemViewWithIdentifier:(NSString *)identifier indexPath:(nonnull NSIndexPath *)indexPath{
    NSDictionary *itemsInfoDic = self.reusableItemViewsEntry[identifier];
    Class itemViewClass = itemsInfoDic[@"class"];
    NSMutableSet *itemViewsSet = itemsInfoDic[@"reusableItemViews"];
    UIView *itemView = nil;
    if (itemViewsSet.count) {
        //获取重用的view
        for (UIView *view in [itemViewsSet allObjects]) {
            if (!view.superview) {
                itemView = view;
                break;
            }
        }
    }
    if (!itemView) {
        itemView = [[itemViewClass alloc] initWithReuseIdentifier:identifier];
    }
    TFTableViewCollectionItem *item = self.collectionItemsArray[indexPath.section];
    item.manager = self;
    itemView.frame = [item.layout.itemFramesArray[indexPath.row] CGRectValue];
    [itemViewsSet addObject:itemView];
    return itemView;
}

- (UIView *)dequeueReusableItemViewWithClass:(Class)aClass indexPath:(nonnull NSIndexPath *)indexPath{
    return [self dequeueReusableItemViewWithIdentifier:NSStringFromClass(aClass) indexPath:indexPath];
}

- (void)registerClass:(Class)aClass forItemViewReuseIdentifier:(NSString *)identifier {
    [self.reusableItemViewsEntry setObject:@{@"class":aClass,@"reusableItemViews":[NSMutableSet set]} forKey:identifier];
}

- (void)registerItemViewWithClass:(Class)aClass {
    [self registerClass:aClass forItemViewReuseIdentifier:NSStringFromClass(aClass)];
}


#pragma mark - lazy load.

- (NSMutableDictionary *)reusableItemViewsEntry {
    if (!_reusableItemViewsEntry) {
        _reusableItemViewsEntry = [NSMutableDictionary dictionary];
    }
    return _reusableItemViewsEntry;
}

@end
